package com.video.commons.systemlog;

import com.video.commons.loginaop.LoginContact;
import com.video.commons.runtimelog.RunLogUtil;
import com.video.entity.Systemlog;
import com.video.entity.User;
import com.video.entity.Webcon;
import com.video.service.system.ISystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author ken
 * @Time 2018/11/8 15:35
 * @Version 1.0
 */
@Aspect
@Component
@Slf4j
@Order(300)
public class LogAop {

    @Autowired
    private ISystemLogService logService;

    @Around("@annotation(SysLog)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取目标方法上的自定义注解IsLogin
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = method.getAnnotation(SysLog.class);

        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();

        //创建系统日志对象
        Systemlog systemLog = new Systemlog();
        systemLog.setTime(new Date());
        systemLog.setType(sysLog.value().getType());
        systemLog.setInfo(sysLog.info());
        //获取登录用户
        systemLog.setUser(getUser(session, sysLog.isBack()));

        Object result = "error";
        try {
            result = joinPoint.proceed();
            systemLog.setFlag(1);//成功
        } catch (Throwable throwable) {
            systemLog.setFlag(0);//失败
            systemLog.setException(throwable.toString());

            //异常继续上抛
            throw throwable;
        } finally {
            try {
                //获取登录用户
                systemLog.setUser(getUser(session, sysLog.isBack()));

                //保存系统日志
                logService.insertLog(systemLog);
            } catch (Exception e) {
                RunLogUtil.error("记录系统日志出现异常", e);
            }
        }

        return result;
    }

    /**
     * 获得登录的用户信息（后台用户 或者 分控）
     * @return
     */
    private String getUser(HttpSession httpSession, boolean isBack){

        if(isBack){
            //当前是后台程序
            User user = (User) httpSession.getAttribute(LoginContact.BACK_USER.getKey());
            if(user != null){
                //如果是后台用户
                return user.getUsername() + "(" + user.getName() + ")";
            }
        } else {
            //当前是分控程序
            Webcon webcon = (Webcon) httpSession.getAttribute(LoginContact.WEBCON_USER.getKey());
            if(webcon != null){
                //如果是分控用户
                return webcon.getAccount() + "(" + webcon.getNickname() + ")";
            }
        }

        return null;
    }
}
